#include "util.h"

#include <string.h>

gchar *nutstore_util_sanitize(const gchar *a) 
{
    g_return_val_if_fail (a != NULL, NULL);

    /* this function escapes following utf-8 characters:
     * '\\', '\n', '\t'
     */
    const guchar *p = (guchar *)a;

    gchar *dest;
    gchar *q;

    q = dest = g_malloc (strlen(a) * 2 + 1); 

    while (*p) {
        switch (*p) {
            case '\\':
                *q++ = '\\';
                *q++ = '\\';
                break;
            case '\n':
                *q++ = '\\';
                *q++ = 'n';
                break;
            case '\t':
                *q++ = '\\';
                *q++ = 't';
                break;

            default:
                *q++ = *p;
                break;
        }
        p++;
    }
    *q = 0;

    return dest;
}

gchar *nutstore_util_desanitize(const gchar *a) 
{
    return g_strcompress(a);
}

gboolean nutstore_util_command_parse_arg(const gchar *line, 
        GHashTable *return_table) 
{
    gchar **argval;
    guint len;
    gboolean retval;

    argval = g_strsplit(line, "\t", 0);
    len = g_strv_length(argval);

    /*  debug("parsed: (%d) %s", len, line); */

    if (len > 1) {
        int i;
        gchar **vals;

        vals = g_new(gchar *, len);
        vals[len-1] = NULL;

        for (i = 1; argval[i] != NULL; i++) {
            vals[i-1] = nutstore_util_desanitize(argval[i]);
        }

        g_hash_table_insert(return_table,
                nutstore_util_desanitize(argval[0]),
                vals);
        retval = TRUE;
    } else {
        retval = FALSE;
    }

    g_strfreev(argval);
    return retval;
}
